//
//  SHDiscoverSearchView.swift
//  SHWeibo
//
//  Created by jingming wang on 16/7/27.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit

class SHDiscoverSearchView: UIView {
    
    //MARK: - 懒加载控件
    // 取消按钮
    private lazy var cancelButton: UIButton = UIButton(title: "取消", titleColor: K_THEME_COLOR, font: 15, target: self, action: "didClickButton")
    //输入框
    private lazy var textField: UITextField = {
        let imgV = UIImageView(imgName: "searchbar_textfield_search_icon")
        imgV.contentMode = .Center
        imgV.frame.size = CGSize(width: 35, height: 35)
        let tf = UITextField()
        tf.layer.borderColor = K_THEME_COLOR.CGColor
        tf.layer.borderWidth = 2
        tf.placeholder = "上海传智IOS三期"
        tf.backgroundColor = UIColor.whiteColor()
        tf.leftView = imgV
        tf.leftViewMode = .Always
        tf.delegate = self
        return tf
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: K_SCREEN_WIDTH, height: 35))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = RandomColor()
        // 添加控件
        addSubview(cancelButton)
        addSubview(textField)
        // 添加约束
        cancelButton.snp_makeConstraints { (make) -> Void in
            make.width.equalTo(50)
            make.top.bottom.trailing.equalTo(self)
        }
        textField.snp_makeConstraints { (make) -> Void in
            make.top.leading.bottom.equalTo(self)
            make.trailing.equalTo(self)
        }
        
    }
    // MARK: - 监听方法
    func didClickButton(){
        // 更新约束
        self.textField.snp_updateConstraints { (make) -> Void in
            make.trailing.equalTo(self)
        }
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.layoutIfNeeded()
            }) { (_) -> Void in
                // 取消第一响应者
                self.textField.resignFirstResponder()
        }
    }
}
//MARK: - Delegate
extension SHDiscoverSearchView: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(textField: UITextField) {
        self.textField.snp_updateConstraints { (make) -> Void in
            make.trailing.equalTo(self).offset(-50)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.layoutIfNeeded()
        }
    }
}
